package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderInfoService;
import domain.OrderInfo;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_DELAY_GROUP,
        topic = MQConstans.CREATE_ORDER,
        selectorExpression = MQConstans.CREATE_ORDER_DELAY_TAG

)

@Component
public class OrderSuccessDelayMQListener implements RocketMQListener<Map> {

    @Autowired

    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ISeckillOrderInfoService seckillOrderInfoService;
    @Autowired
    private ISeckillGoodService seckillGoodService;

    @Override
    public void onMessage(Map  map) {
        System.out.println("进入到延迟消费者中");
        //消息是map类型的时候存在这么一个情况
        //如果你的map中key   value中有int long ,它内部进行一个转换如果长度比较小的,认为你是一个int类型
        //如果你的长度比较大它认为是long 类型
        Object seckillId =  map.get("seckillId");
        String orderNo=map.get("data").toString();//拿到订单编号
        Long goodId=null;
        //提高传输效率
        if(seckillId instanceof  Long){
            goodId=(Long)seckillId;

        }else if(seckillId instanceof  Integer){

            goodId=((Integer) seckillId).longValue();

        }
        //1.修改订单状态为超时未支付   where  status=0
        int count = seckillOrderInfoService.changOrderInfoStatus(orderNo, OrderInfo.STATUS_TIMEOUT);//超时未支付
        //如果count!=0说明未付款
        if(count !=0){
        //2,如果没有支付,回补真实库存,回补预库存,修改本地标识
            seckillGoodService.incrCount(goodId);//回补真实库存
            seckillGoodService.syncPreCount(goodId);//回补预库存
            //修改本地标识
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_BROAD_DEST,goodId);//发送广播消息
        }
    }
}